package com.ia.aistream.controller.common;

import java.util.List;

import com.ia.aistream.common.annotation.Log;
import com.ia.aistream.common.config.Global;
import com.ia.aistream.common.enums.ResponeCodeMsgEnums;
import com.ia.aistream.common.utils.StringUtils;
import com.ia.aistream.common.utils.file.FileUtils;
import com.ia.aistream.manager.common.ICommonFileManager;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ia.aistream.common.enums.BusinessType;
import com.ia.aistream.model.common.entity.CommonFile;
import com.ia.aistream.common.core.controller.BaseController;
import com.ia.aistream.common.core.domain.AjaxResult;
import com.ia.aistream.common.utils.poi.ExcelUtil;
import com.ia.aistream.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 系统文件路径Controller
 * 
 * @author aistream
 * @date 2020-12-07
 */
@Controller
@RequestMapping("/common/file")
public class CommonFileController extends BaseController
{
    private String prefix = "common/file";

    @Autowired
    private ICommonFileManager commonFileService;

    @RequiresPermissions("common:file:view")
    @GetMapping()
    public String file()
    {
        return prefix + "/file";
    }

    /**
     * 查询系统文件路径列表
     */
    @RequiresPermissions("common:file:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CommonFile commonFile)
    {
        startPage();
        List<CommonFile> list = commonFileService.selectCommonFileList(commonFile);
        return getDataTable(list);
    }

    /**
     * 导出系统文件路径列表
     */
    @RequiresPermissions("common:file:export")
    @Log(title = "系统文件路径", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CommonFile commonFile)
    {
        List<CommonFile> list = commonFileService.selectCommonFileList(commonFile);
        ExcelUtil<CommonFile> util = new ExcelUtil<CommonFile>(CommonFile.class);
        return util.exportExcel(list, "file");
    }

    /**
     * 新增系统文件路径
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存系统文件路径
     */
    @RequiresPermissions("common:file:add")
    @Log(title = "系统文件路径", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CommonFile commonFile)
    {
        return toAjax(commonFileService.insertCommonFile(commonFile));
    }

    /**
     * 修改系统文件路径
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        CommonFile commonFile = commonFileService.selectCommonFileById(id);
        mmap.put("commonFile", commonFile);
        return prefix + "/edit";
    }

    /**
     * 修改保存系统文件路径
     */
    @RequiresPermissions("common:file:edit")
    @Log(title = "系统文件路径", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CommonFile commonFile)
    {
        return toAjax(commonFileService.updateCommonFile(commonFile));
    }

    /**
     * 删除系统文件路径
     */
    @RequiresPermissions("common:file:remove")
    @Log(title = "系统文件路径", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(commonFileService.deleteCommonFileByIds(ids));
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        return AjaxResult.success(ResponeCodeMsgEnums.OK.getErrmsg(),commonFileService.upload(file));
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     *
     */
    @GetMapping("/download/{fileType}/{year}/{month}/{date}/{fileName}")
    public void fileDownload(@PathVariable("fileType")String fileType,
                             @PathVariable("year")String year,
                             @PathVariable("month")String month,
                             @PathVariable("date")String date,
                             @PathVariable("fileName")String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception
    {

//        if (!FileUtils.isValidFilename(fileName))
//        {
//            throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
//        }
        String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
        String filePath = Global.getProfile() + "/" + fileType + "/" + year
                + "/" + month + "/" + date + "/" + fileName;

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
        FileUtils.writeBytes(filePath, response.getOutputStream());
    }
}
